<script setup>
	import { groupLogin, codeLogin, tokenLogin } from './http/apis.js';
	import {
		onLaunch,
		onShow
	} from '@dcloudio/uni-app'
	import { useMutations } from './store/hooks/useMutations';
	import {getCurrentInstance} from 'vue'
	const { proxy } = getCurrentInstance();
	const { $isResolve } = proxy;
	
	const { setToken, setUser, setConfigs, setInviter, setIsLeader, setHasShop, setFranchisee, setLeaderId, setCarts } = useMutations(['setToken', 'setUser', 'setConfigs', 'setInviter', 'setIsLeader', 'setHasShop','setFranchisee', 'setLeaderId','setCarts']);
	const globalData = {
		inviter: 0, // 邀请人id
		user: null,
		redirect_scan_time: "", // 是否已经跳转过了,
		pay_status: 0, // 0初始状态 1支付成功 2支付失败或者取消支付
		payment_no: '',
		categories: [],
		statusBarHeight: 47,
		navBarHeight: 40,
		category_id: 0,
		chooseHide: false, // chooseMedia等操作会触发onShow,此类操作禁止执行onShow逻辑
	}
	onLaunch((options) => {
		// #ifdef MP-WEIXIN
		const accountInfo = uni.getAccountInfoSync();
		if (accountInfo && accountInfo.miniProgram.envVersion == 'release') {
			uni.getBackgroundFetchData({
				  fetchType: 'pre',
				  success(res) {
					  const st = new Date().getTime() - res.timeStamp
					  console.log("=====fetchedData success:", st)
					  if (st < 5 * 60 * 1000) {
						  const fd = JSON.parse(res.fetchedData)
						  if (fd.code === 0) {
							uni.setStorageSync('fetched-data', fd.data);
						  }
					  } else {
						  console.log("getBackgroundFetchData expired:", st)
					  }
				  },
				  fail(res){
					  uni.removeStorageSync('fetched-data')
					  console.log(res, "=====fetchedData fail")
				  }
			})
		}
		// #endif
		
		console.log('App Launch', options)
	})
	onShow((options) => {
		console.log('App Show', options)
		if (globalData.chooseHide) {
			globalData.chooseHide = false;
			return;
		}
		
		getOptionsQuery(options)
		const { statusBarHeight } = uni.getSystemInfoSync();
		// #ifdef MP-WEIXIN
		const {top, height} = uni.getMenuButtonBoundingClientRect();
		const navBarHeight = height + (top - statusBarHeight) * 2;
		globalData.navBarHeight = navBarHeight || 0;
		// #endif
		globalData.statusBarHeight = statusBarHeight;
		
		if (options.chatType && (options.chatType === 3 || options.chatType === 4)) {
			uni.getGroupEnterInfo({
				success: (res) => {
					wxgroupLogin(res)
				},
				fail: (res) => {
					let token = uni.getStorageSync('token');
					if (token) {
					   wxtokenLogin(token)
					}else{
					   authLogin()
					}
				}
			})
		} else {
			let token = uni.getStorageSync('token');
			if (token) {
			   wxtokenLogin(token)
			}else{
			   authLogin()
			}
		}
	})
	
	// 获取code
	const authLogin = () => {
		uni.login({
			provider: "weixin",
			success: function(res) {
				wxcodeLogin(res.code)
			},
			fail: function(res) {
				console.log(res);
			}
		})
	}
	
	const wxgroupLogin = (groupRes) => {
		uni.login({
			provider: "weixin",
			success: function(res) {
				groupLogin({
					code: res.code,
					inviter: parseInt(globalData.inviter),
					encripty_data: groupRes.encryptedData,
					iv: groupRes.iv
				}).then(res => {
					loginSuccess(res)
				}).catch(res => {
					console.log(res);
					uni.showToast({
						icon: 'none',
						title: res.msg || '微信登录失败'
					})
				})
			},
			fail: function(res) {
				console.log(res);
			}
		})
	}

	// 微信授权code登录
	const wxcodeLogin = (code) => {
		codeLogin({code: code, inviter: parseInt(globalData.inviter)}).then(res => {
			loginSuccess(res)
		}).catch(res => {
			console.log(res);
			uni.showToast({
				icon: 'none',
				title: res.msg || '微信登录失败'
			})
		})
	}
	// token登录
	const wxtokenLogin = (token) => {
		tokenLogin({tk: token,inviter: parseInt(globalData.inviter)}).then(res => {
			loginSuccess(res)
		}).catch(res => {
			console.log('fail---', res);
			authLogin();
		})
	}
	// 登录成功回调
	const loginSuccess = (res) => {
		uni.setStorageSync('token', res.token);
		setToken(res.token)
		setUser(res.user_info);
		setConfigs(res.configs); // 获取全局配置
		setIsLeader(res.share_user_is_leader) // 团长分享
		setLeaderId(res.leader_id);
		setFranchisee(res.franchisee_id);
		setHasShop(res.has_shop)
		setInviter(res.inviter);
		globalData.user = res.user_info.user;
		
		let carts = uni.getStorageSync('carts');
		if (carts) {
			let cartsArr = JSON.parse(uni.getStorageSync('carts')) || [];
			setCarts(cartsArr);
		}
		checkForUpdate(); // 检查新版本
		$isResolve();
	}
	
	// 检查新版本
	const checkForUpdate = () => {
		const updateManager = uni.getUpdateManager();
		updateManager.onCheckForUpdate(function(res) {
			// 请求完新版本信息的回调
			// console.log(res.hasUpdate);
		});
		updateManager.onUpdateReady(function(res) {
			uni.showModal({
				title: '更新提示',
				content: '新版本已经准备好，是否重启应用？',
				success(res) {
					if (res.confirm) {
						// 新的版本已经下载好，调用 applyUpdate 应用新版本并重启
						updateManager.applyUpdate();
					}
				}
			});
		});
		updateManager.onUpdateFailed(function(res) {
			// 新的版本下载失败
		});
	}
	// onLanuch onShow时都需要获取分享参数
	const getOptionsQuery = (options) => {
		// 半屏支付回调传参
		if (options.referrerInfo.appId === 'wxf0286c0d3b87bf34' ) {
			if (options.referrerInfo.extraData) {
				globalData.pay_status = options.referrerInfo.extraData.status;
				globalData.payment_no = options.referrerInfo.extraData.payment_no;
			} else {
				globalData.pay_status = 2;
				globalData.payment_no = '';
			}
			return;
		}
		
		let url = (options.query && options.query['url']) ? options.query['url'] : "";
		let inviter = (options.query && options.query['inviter']) ? parseInt(options.query['inviter']) : 0;
		let scanTime = new Date
		if (inviter === 0 && options.query.q) {
			if (options.query.q.substring(0,4) === "http") {
				const q = decodeURIComponent(options.query.q)
				const idx = q.indexOf("?")
				let search = q.substring(idx+1)
				const params = search.split("&")
				params.forEach((p) => {
					const idx = p.indexOf("=")
					const key = p.substring(0, idx)
					const value = p.substring(idx+1)
					if (key === "inviter") {
						inviter = parseInt(value) || 0
					}
					if (key === "url") {
						url = new Buffer(value, 'base64').toString('utf8')
						// url = atob(value)
					}
				})
			}
		}
		globalData.inviter = inviter || 0;
		// setInviter(globalData.inviter);
	
		const scene = options.scene;
		const urlScene = getUrlParams(url, 'scene');
		console.log('App url:', url, 'scene:', scene, 'urlScene:', urlScene);
		if (url && (urlScene.indexOf(scene) > -1 || !urlScene)) { // 避免扫码进入的时候，再次跳转到支付页
			if (options.query.scancode_time) {
				if (globalData.scancode_time == options.query.scancode_time) {
					return
				}
				globalData.scancode_time = options.query.scancode_time
			}
			setTimeout(() => {
				uni.navigateTo({
					url: url
				})
			}, 100)
		}
	}
	// 获取URL 指定参数
	const getUrlParams = (url, name) =>  {
			let context = '';
			if (url.indexOf("?") != -1) {
				const str = url.substr(1);
				const reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
				const r = str.match(reg);
				if (r != null) {
					context = decodeURIComponent(r[2])
				}
			}
			return context;
		}
</script>

<style>
	/*每个页面公共css */
	::-webkit-scrollbar {
		width: 0 !important;
		height: 0 !important;
		color: transparent;
	}
	::v-deep .uni-nav-bar-text{
		font-size: 36rpx !important;
	}

</style>
